package com.yn.xgame;

import com.yn.xgame.po.LoadInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * LoadInfoManager
 * Created by wangboo on 2017/7/12.
 */
public class LoadInfoManager {

    private static final Logger logger = LoggerFactory.getLogger(LoadInfoManager.class);
    private List<LoadInfo> curLoadList;
    private List<LoadInfo> workingList;

    public LoadInfoManager() {
        curLoadList = new ArrayList<>();
        workingList = new ArrayList<>();
    }

    public void reset(List<LoadInfo> all) {
        curLoadList.clear();
        curLoadList.addAll(all);
        recalc();
    }

    public void addOrUpdate(LoadInfo info) {
        Optional<LoadInfo> os = curLoadList.stream().filter(s -> s.id == info.id).findFirst();
        if(os.isPresent()) {
            os.get().cur = info.cur;
            os.get().max = info.max;
            os.get().state = info.state;
        } else {
            curLoadList.add(info);
        }
        recalc();
    }

    private void recalc() {
        workingList.clear();
        curLoadList.forEach(s -> {
            if (s.isWorking()) workingList.add(s);
        });
        workingList.sort(null);
    }

    public void remove(int id) {
        curLoadList.removeIf(s -> s.id == id);
        workingList.removeIf(s -> s.id == id);
    }

    public List<LoadInfo> getWorkingList() {
        return workingList;
    }

    public void report() {
        logger.info("LoadInfo size: {}", curLoadList.size());
        curLoadList.forEach(s -> logger.info(s.toString()));
    }

    public String getopicById(int id) {
        Optional<LoadInfo> oi = workingList.stream().filter(l -> l.id == id).findFirst();
        if (oi.isPresent()) return oi.get().topic;
        return null;
    }
}
